package ru.xrm.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.xrm.selenium.model.ShortFilmInfo;

public class HomePage extends InternalPage {

	public HomePage(PageManager pages) {
		super(pages);
	}

	@Override
	public HomePage ensurePageLoaded() {
		super.ensurePageLoaded();
		wait.until(presenceOfElementLocated(By.xpath("//div[contains(@id,'movie_')]")));
		return this;
	}

	public HomePage ensureSearchEnded()
	{
		super.ensurePageLoaded();
		wait.until(presenceOfElementLocated(By.xpath("//div[@id='results']")));
		return this;
	}

	@FindBy(xpath = "//*[@id='wrapper']/header/div/nav/ul/li[1]/a")
	private WebElement homePageLink;

	@FindBy(css = "img[alt=\"Add movie\"]")
	private WebElement addMovieLink;

	@FindBy(id = "q")
	private WebElement searchLine;

	@FindBy(xpath = "//div[contains(@id,'movie_')]")
	private List<WebElement> listOfFilms;

	public AddNewFilmPage clickAddMovieLink()
	{
		addMovieLink.click();
		return pages.addNewFilmPage;
	}

	public List<ShortFilmInfo> getShortFilmsListInfo()
	{
		List<ShortFilmInfo> shortFilmsInfoList = new ArrayList<ShortFilmInfo>();
		try
		{
			for (WebElement webElementFilm : listOfFilms)
			{
				ShortFilmInfo shotFilmInfo = new ShortFilmInfo();
				shotFilmInfo.setId(webElementFilm.getAttribute("id"))
				.setName(webElementFilm.findElements(By.tagName("div")).get(2).getText());		
				shortFilmsInfoList.add(shotFilmInfo);
			}	  
		}
		catch(WebDriverException e)
		{
			return null;
		}
		return shortFilmsInfoList;
	}

	public ViewFilmInfoPage goToFilmInfo(ShortFilmInfo film)
	{
		try
		{
			WebElement refToFullFulmInfo = driver.findElement(By.id(film.getId()));
			refToFullFulmInfo.click();
			return pages.viewFilmInfoPage.ensurePageLoaded();
		}
		catch(WebDriverException e)
		{
			return null;
		}
	}

	public String getSearchLine() {
		return searchLine.getText();
	}

	public HomePage setSearchLine(String NameFilm) {
		searchLine.clear();
		searchLine.sendKeys(NameFilm);
		return this;
	}

	public HomePage startSearch()
	{
		searchLine.sendKeys(Keys.RETURN);
		ensureSearchEnded();
		return this;
	}
}
